package controller

import (
	"doctor_api_backend/config"
	model "doctor_api_backend/models"
	"net/http"

	"github.com/gin-gonic/gin"
)

// 查询病人信息 by patientCode
func GetPatient(c *gin.Context) {
	patientCode := c.Param("patientCode")
	var patient model.Patient
	if err := config.DB.Where("patient_code = ?", patientCode).First(&patient).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "病人不存在"})
		return
	}
	c.JSON(http.StatusOK, patient)
}

// 查询所有病人信息
func GetAllPatients(c *gin.Context) {
	var patients []model.Patient
	if err := config.DB.Find(&patients).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取病人失败"})
		return
	}
	c.JSON(http.StatusOK, patients)
}

// 创建病人
func CreatePatient(c *gin.Context) {
	var patient model.Patient
	if err := c.ShouldBindJSON(&patient); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	config.DB.Create(&patient)
	c.JSON(http.StatusCreated, patient)
}

// 更新病人 通过patient_code更新病人
func UpdatePatient(c *gin.Context) {
	patientCode := c.Param("patientCode")
	var patient model.Patient
	if err := config.DB.Where("patient_code = ?", patientCode).First(&patient).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "病人不存在"})
		return
	}

	var updatedPatient model.Patient
	if err := c.ShouldBindJSON(&updatedPatient); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}

	config.DB.Model(&patient).Updates(updatedPatient)
	c.JSON(http.StatusOK, patient)
}

// 删除病人 通过patient_code删除病人
func DeletePatient(c *gin.Context) {
	patientCode := c.Param("patientCode")
	var patient model.Patient
	if err := config.DB.Where("patient_code = ?", patientCode).First(&patient).Error; err != nil {
		c.JSON(http.StatusNotFound, gin.H{"error": "病人不存在"})
		return
	}

	config.DB.Delete(&patient)
	c.JSON(http.StatusOK, gin.H{"message": "病人删除成功"})
}

// 查询病人药物 通过patient_code查询病人药物
func GetPatientMedicines(c *gin.Context) {
	patientCode := c.Param("patientCode")
	var medicines []model.Medicine

	if err := config.DB.Where("patient_code = ?", patientCode).Find(&medicines).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取病人药品失败"})
		return
	}
	c.JSON(http.StatusOK, medicines)
}

// 查询病人病历记录 通过patient_code查询病人病历记录
func GetPatientMedicalRecords(c *gin.Context) {
	patientCode := c.Param("patientCode")
	var records []model.MedicalRecord

	if err := config.DB.Where("patient_code = ?", patientCode).Find(&records).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取病人病历记录失败"})
		return
	}
	c.JSON(http.StatusOK, records)
}

// 查询病人医生 通过patient_code查询病人医生
func GetPatientDoctors(c *gin.Context) {
	patientCode := c.Param("patientCode")
	var doctors []model.Doctor

	if err := config.DB.Where("patient_code = ?", patientCode).Find(&doctors).Error; err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "获取病人医生失败"})
		return
	}
	c.JSON(http.StatusOK, doctors)
}
